package com.atguigu.web;

import com.atguigu.pojo.impl.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获得请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用userService.Login()登录处理业务
        User loginUser = userService.login(new User(null,username,password,null));
        //如果等于null，说明登录失败
        if (loginUser == null){
            //跳回登录页面
            //把错误信息，和回显的表单项信息，保存到Request域中
            request.setAttribute("msg","用户或密码错误!");
            request.setAttribute("username",username);
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
        }else {
            //登录 成功
            //保存用户登录的信息到Session域中
            request.getSession().setAttribute("user",loginUser);
            //跳到成功页面login_success.html
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request,response);
        }
    }

}
